package com.genersoft.iot.vmp.utils;



import com.alibaba.fastjson.JSON;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;

import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.net.ConnectException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class HttpUtil{
    private final static Logger logger = LoggerFactory.getLogger(HttpUtil.class);

    public static void main(String[] args) throws Exception {
        /**
         *请求
         */
//        String url = "http://localhost:8080/a/a";
//        Map<String, String> map = new HashMap<String, String>();
//        map.put("cardNo", "6221506020009066385");
//        map.put("cardBinCheck", "true");
//        String json_Str = send(url, map, "utf-8");
//        JSONObject json_obj= JSONObject.parseObject(json_Str);
//        //System.out.println(json_obj.get("bank")+"");

        Map<String,Object> alarmParam = new HashMap();//BeanUtils.describe(deviceAlarm);

        alarmParam.put("acct", "34020000001320000005");
        alarmParam.put("longitude", 0);
        alarmParam.put("latitude", 0);
        alarmParam.put("eventId", 111);
        alarmParam.put("eventMsg", "");
        alarmParam.put("eventDesc", "");
        alarmParam.put("eventTime", "2021-12-24 11:11:11");
        alarmParam.put("eventImageUrl", "http://local");
        alarmParam.put("eventVedioUrl", "");
        alarmParam.put("isRejectedEventVedio", 1);
        String alarmMethod = "1";
        if (!StringUtils.isEmpty(alarmMethod)) {
            if ("6".equals(alarmMethod)) {
                alarmMethod = "3";
            } else {
                alarmMethod = "1";
            }
        }
        alarmParam.put("eventType", alarmMethod);
        String s = JSONObject.toJSONString(alarmParam);
        System.out.println(s);
        JSONObject json = new JSONObject(alarmParam);
        System.out.println(json);

        // String json_Str = sendForJson("http://47.115.127.132/api/aqy-backgrnd-mgmt/deviceevent-manager/addDeviceEvent", alarmParam, "utf-8");
    }

    /**
     * 请求
     *
     * @param url
     *            资源地址
     * @param map
     *            参数列表
     * @param encoding
     *            编码
     * @return
     */
    public static String send(String url, Map<String, String> map, String encoding) throws IOException {
        String body = "";

        // 创建httpclient对象
        CloseableHttpClient client = HttpClients.createDefault();

        // 创建post方式请求对象
        HttpPost httpPost = new HttpPost(url);

        //配置超时
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(3000).setConnectionRequestTimeout(3000)
                .setSocketTimeout(3000).build();
        httpPost.setConfig(requestConfig);

        if(StringUtils.isEmpty(encoding)){
            encoding = "utf-8";
        }

        // 装填参数
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        if (map != null) {
            for (Map.Entry<String, String> entry : map.entrySet()) {
                nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
        }
        // 设置参数到请求对象中
        httpPost.setEntity(new UrlEncodedFormEntity(nvps, encoding));

        // 设置header信息
        // 指定报文头【Content-type】、【User-Agent】
        httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");

        // 执行请求操作，并拿到结果（同步阻塞）
        CloseableHttpResponse response = client.execute(httpPost);

        if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
           // logger.info("URL请求成功："+url);
        }else{
            logger.error("URL请求失败："+url);
        }
       /* // 获取结果实体
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            // 按指定编码转换结果实体为String类型
            body = EntityUtils.toString(entity, encoding);
        }
        EntityUtils.consume(entity);
        // 释放链接
        response.close();*/
        return body;
    }


    public static String sendForJson(String url, String json, String encoding) throws IOException {
        String body = "";

        // 创建httpclient对象
        CloseableHttpClient client = HttpClients.createDefault();

        // 创建post方式请求对象
        HttpPost httpPost = new HttpPost(url);

        //配置超时
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(3000).setConnectionRequestTimeout(3000)
                .setSocketTimeout(3000).build();
        httpPost.setConfig(requestConfig);

        if(StringUtils.isEmpty(encoding)){
            encoding = "utf-8";
        }
        StringEntity entity = new StringEntity(json, encoding);
        httpPost.setEntity(entity);
        // 设置header信息
        // 指定报文头【Content-type】、【User-Agent】
        httpPost.setHeader("Content-type", "application/json");

        // 执行请求操作，并拿到结果（同步阻塞）
        CloseableHttpResponse response = client.execute(httpPost);

        if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
            HttpEntity entityRe = response.getEntity();
            if (entityRe != null) {
                // 按指定编码转换结果实体为String类型
                body = EntityUtils.toString(entityRe, encoding);
                logger.info("URL请求成功："+body);
            }
            // logger.info("URL请求成功："+url);
        }else{
            logger.error("URL请求失败："+url);
        }
       /* // 获取结果实体
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            // 按指定编码转换结果实体为String类型
            body = EntityUtils.toString(entity, encoding);
        }
        EntityUtils.consume(entity);*/
        // 释放链接
        response.close();
        return body;
    }

    private void sendTest(){
        Map<String,Object> alarmParam = new HashMap();//BeanUtils.describe(deviceAlarm);

            alarmParam.put("acct", "34020000001320000005");
            alarmParam.put("longitude", 0);
            alarmParam.put("latitude", 0);
            alarmParam.put("eventId", 111);
            alarmParam.put("eventMsg", "");
            alarmParam.put("eventDesc", "");
            alarmParam.put("eventTime", "2021-12-24 11:11:11");
            alarmParam.put("eventImageUrl", "");
            alarmParam.put("eventVedioUrl", "");
            alarmParam.put("isRejectedEventVedio", 1);
            String alarmMethod = "1";
            if (!StringUtils.isEmpty(alarmMethod)) {
                if ("6".equals(alarmMethod)) {
                    alarmMethod = "3";
                } else {
                    alarmMethod = "1";
                }
            }
            alarmParam.put("eventType", alarmMethod);

        //HttpUtil.send("http://47.115.127.132/api/aqy-backgrnd-mgmt/deviceevent-manager/addDeviceEvent",alarmParam,"utf-8");
        OkHttpClient client = new OkHttpClient();
        String url = "http://47.115.127.132/api/aqy-backgrnd-mgmt/deviceevent-manager/addDeviceEvent";
        JSONObject responseJSON = null;
        logger.debug(url);

        FormBody.Builder builder = new FormBody.Builder();
        if (alarmParam != null && alarmParam.keySet().size() > 0) {
            for (String key : alarmParam.keySet()){
                if (alarmParam.get(key) != null) {
                    builder.add(key, alarmParam.get(key).toString());
                }
            }
        }

        FormBody body = builder.build();

        okhttp3.Request request = new okhttp3.Request.Builder()
                .post(body)
                .url(url)
                .build();
        try {
            okhttp3.Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                logger.info("告警推送点汇平台成功");
            }else{
                logger.info("告警推送点汇平台失败"+ response.message()+"-"+response.code());
            }
        } catch (ConnectException e) {
            logger.error(String.format("告警推送点汇平台失败: %s, %s", e.getCause().getMessage(), e.getMessage()));
        }catch (IOException e) {
            logger.error(String.format("[ %s ]告警推送点汇平台失败: %s", url, e.getMessage()));
        }

    }



}